<template>
  <el-form ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form">
    <h3 class="title">{{ title }}</h3>
    <el-form-item prop="username">
      <el-input v-model="loginForm.username" type="text" auto-complete="off" placeholder="账号">
        <svg-icon slot="prefix" icon-class="user" class="el-input__icon input-icon"/>
      </el-input>
    </el-form-item>
    <el-form-item prop="password">
      <el-input
        v-model="loginForm.password"
        type="password"
        auto-complete="off"
        placeholder="密码"
        @keyup.enter.native="handleLogin"
      >
        <svg-icon slot="prefix" icon-class="password" class="el-input__icon input-icon"/>
      </el-input>
    </el-form-item>
    <template v-if="captchaOnOff">
      <el-form-item v-if="isImgCaptcha" prop="code">
        <el-input
          v-model="loginForm.code"
          auto-complete="off"
          placeholder="验证码"
          style="width: 63%"
          @keyup.enter.native="handleLogin"
        >
          <svg-icon slot="prefix" icon-class="validCode" class="el-input__icon input-icon"/>
        </el-input>
        <div class="login-code">
          <img :src="codeUrl" @click="getCode" class="login-code-img"/>
        </div>
      </el-form-item>
      <template v-else>
        <el-button v-if="isSlideValid" type="success" icon="el-icon-finished" style="width: 100%;margin-bottom: 15px">已完成安全验证</el-button>
        <el-button v-else type="info" icon="el-icon-thumb" style="width: 100%;margin-bottom: 15px" @click="showValidCaptcha">请进行安全验证</el-button>
        <Verify
          @success="captchaCheckSuccess"
          :mode="'pop'"
          :captchaType="captchaType"
          :imgSize="{ width: '330px', height: '155px' }"
          ref="verify"
        ></Verify>
      </template>
    </template>

    <el-form-item style="width:100%;">
      <el-button
        :loading="loading"
        size="medium"
        type="primary"
        style="width:100%;"
        @click.native.prevent="handleLogin"
      >
        <span v-if="!loading">登 录</span>
        <span v-else>登 录 中...</span>
      </el-button>
      <div style="float: right;" v-if="register">
        <router-link class="link-type" :to="'/register'">立即注册</router-link>
      </div>
    </el-form-item>

    <!--插入-->
    <slot/>
  </el-form>
</template>

<script>
import {getCodeImg, getCaptchaType} from "@/api/login";
import Verify from "@/components/Verifition/Verify";

import {validPassword} from "@/utils/validate";

export default {
  name: "LoginFormUserName",
  components: {Verify},
  data() {
    return {
      title: process.env.VUE_APP_TITLE || '[[数研脚手架]]系统',
      captchaType: 'math',
      isImgCaptcha: true,
      isSlideValid: false,
      codeUrl: "",
      loginForm: {
        username: "",
        password: "",
        code: "",
        uuid: "",

        loginType: 'userName'
      },
      loginRules: {
        username: [
          {required: true, trigger: "blur", message: "请输入您的账号"}
        ],
        password: [
          {required: true, trigger: "blur", message: "请输入您的密码"}
        ],
        code: [{required: true, trigger: "change", message: "请输入验证码"}]
      },
      loading: false,
      // 验证码开关
      captchaOnOff: true,
      // 注册开关
      register: false,
      redirect: undefined
    };
  },
  watch: {
    $route: {
      handler: function (route) {
        this.redirect = route.query && route.query.redirect;
      },
      immediate: true
    }
  },
  async mounted() {
    //验证码开关
    await this.getCaptchaOnOff();
    //验证码类型
    let captchaType = (await getCaptchaType()).msg;
    this.captchaType = captchaType;
    if (captchaType == 'math' || captchaType == 'char') {
      //图片验证================================================
      this.isImgCaptcha = true;
      this.isSlideValid = true;
      this.getCode();
    } else if (captchaType == 'blockPuzzle' || captchaType == 'clickWord') {
      //滑块验证 ================================================
      this.isImgCaptcha = false;

    }
  },
  methods: {
    getCode() {
      getCodeImg().then(res => {
        this.captchaOnOff = res.captchaOnOff === undefined ? true : res.captchaOnOff;
        if (this.captchaOnOff) {
          this.codeUrl = "data:image/gif;base64," + res.img;
          this.loginForm.uuid = res.uuid;
        }
      });
    },
    //获取验证码开关
    async getCaptchaOnOff() {
      let res = await getCodeImg();
      this.captchaOnOff = res.captchaOnOff === undefined ? true : res.captchaOnOff;
    },
    showValidCaptcha() {
      this.$refs.verify.show();
    },
    captchaCheckSuccess(params) {
      this.loginForm.code = params.captchaVerification;
      this.isSlideValid = true;
    },
    handleLogin() {
      if (this.captchaOnOff && !this.isSlideValid) {
        this.$modal.msgError('请先进行安全验证');
        return false;
      }
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.loading = true;
          this.$store.dispatch("Login", this.loginForm).then(() => {
            //校验是否应该修改密码
            validPassword(this.loginForm.password).then(() => {
              localStorage.setItem('weekPwd', '0');
            }).catch(() => {
              localStorage.setItem('weekPwd', '1');
            })
            //跳转登录
            this.$router.push({path: this.redirect || "/"}).catch(() => {
            });
          }).catch((err) => {
            this.loading = false;
            if (this.captchaOnOff) {
              if (this.isImgCaptcha) {
                this.getCode();
              } else {
                this.isSlideValid = false;
              }
            }
          });
        }
      });
    }
  }
};
</script>
